import DOMPurify from 'dompurify';

export function sanitizeToText(content) {
  return DOMPurify.sanitize(content, { ALLOWED_TAGS: [] });
}

export function sanitizeToHtml(content) {
  return DOMPurify.sanitize(content);
}

/**
 * 编码 html
 * @param e string
 */
export function encodeHTML(e: string) {
  return e
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

/**
 * 过滤 html
 * @param html string
 */
export function filterHTML(html: string) {
  let text = html;
  return (text = text
    .replace(/<\s*script[^>]*>[\s\S]*?<\/script>/gim, '')
    .replace(/<\s*style[^>]*>[\s\S]*?<\/style>/gim, '')
    .replace(/<!--.*?-->/gim, '')
    .replace(/<!DOCTYPE.*?>/gi, '')
    .replace(/<\/div>/gi, '')
    .replace(/(<br><div>|<div>|<br>)/gi, '\n')
    .replace(/&nbsp;/gi, '')
    .replace(/<.*?>/gi, '')
    .replace(/&lt;/gi, '<')
    .replace(/&amp;/gi, '&')
    .replace(/&gt;/gi, '>')
    .replace(/&#39;/gi, "'")
    .replace(/&quot;/g, '"'));
}
